<script setup lang="ts">
  import { ref } from "vue";
  import { ElForm, ElFormItem, ElInput, ElButton, ElLoading } from "element-plus";
  const
    data = ref({
      domain: "",
      websiteName: "",
      csPhone: "",
    }),
    opt = {
      resize: "none",
      autosize: { minRows: 10, maxRows: 10 },
      showWordLimit: true,
      type: "textarea",
    },
    otk = ["merchantSerialCert", "merchantSerialKey"],
    rules = ref<{ [K in Key<typeof data.value>]: { required: true; message: string; opt: obj; } }>()
    ;
  async function init() {
    const r: any = {};
    (await gd.setting.getById(Object.keys(data.value))).forEach(e => {
      // @ts-ignore
      data.value[e.id] = e.value;
      r[e.id] = { required: true, message: "请输入" + e.name };
      if (otk.includes(e.id)) {
        r[e.id].opt = opt;
      }
    });
    rules.value = r;
  }
  init();
  async function refreshClick() {
    const loading = ElLoading.service({ text: "正在还原，请稍后..." });
    for (const id in data.value) {
      const k = id as Key<typeof data.value>, d = await gd.setting.getById(k);
      if (d) {
        data.value[k] = d.value;
      }
    }
    loading.close();
    msg("还原完毕", "success");
  }
  async function save() {
    const loading = ElLoading.service({ text: "正在保存，请稍后..." });
    for (const id in data.value) {
      const k = id as Key<typeof data.value>, d = await gd.setting.getById(k);
      if (d && d.value != data.value[k] && await gd.setting.update({ id, value: data.value[k] })) {
        d.value = data.value[k];
      }
    }
    loading.close();
    msg("保存完毕", "success");
  }
</script>
<template>
  <div class="wx oy">
    <ElForm class="xw zb mt1em" labelWidth="9em" :model="data" :rules="rules">
      <ElFormItem v-for="(i, k) in rules" :prop="k" :label="i.message.substring(3)">
        <ElInput :placeholder="i.message" v-model="data[k]" :="i.opt" />
      </ElFormItem>
    </ElForm>
    <div>
      <ElButton type="success" @click="refreshClick">重置</ElButton>
      <ElButton type="primary" @click="save">保存</ElButton>
    </div>
  </div>
</template>
<style lang="scss" scoped>
  .wx {
    position: relative;
    >:nth-child(1) {
      color: var(--color-info);
      .mac-ico-warning::before {
        color: var(--color-warning);
      }
    }
    >.xw {
      >:not(.wf) {
        width: 49%;
      }
    }
  }
</style>